package cn.szq.springframework.core.io;

import cn.hutool.core.lang.Assert;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

/***
 * All rights Reserved, Designed By www.jx-lab.com
 * @Title: UrlResource
 * @Description:
 * @author lixy
 * @date 2021/8/12 15:53
 * @version V1.0
 * @Copyright: www.jx-lab.com Inc. All rights reserved.
 * 注意：本内容仅限于众合景轩信息技术有限公司内部传阅，禁止外泄以及用于其他的商业目
 */
public class UrlResource implements Resource {

    private final URL url;

    public UrlResource(URL url) {
        Assert.notNull(url, "URL must not be null");
        this.url = url;
    }

    @Override
    public InputStream getInputStream() throws IOException {
        URLConnection urlConnection = this.url.openConnection();
        try{
            return urlConnection.getInputStream();
        }catch (IOException e){
            if (urlConnection instanceof HttpURLConnection){
                ((HttpURLConnection) urlConnection).disconnect();
            }
            throw e;
        }
    }
}
